package com.qzxl.conntext.utils;





import org.junit.platform.commons.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @Auther: jintianyun
 * @Date: 2020/9/11 10:14
 * @Description:
 */
public class Util16 {
    // 16进制字符

    public final static String[] hexArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };


    /**
     * 其他进制转十进制
     * @param number
     * @return
     */
    public static int scale2Decimal(String number, int scale) {
        checkNumber(number);
        if (2 > scale || scale > 32) {
            throw new IllegalArgumentException("scale is not in range");
        }
        // 不同其他进制转十进制,修改这里即可
        int total = 0;
        String[] ch = number.split("");
        int chLength = ch.length;
        for (int i = 0; i < chLength; i++) {
            total += Integer.valueOf(ch[i]) * Math.pow(scale, chLength - 1 - i);
        }
        return total;

    }

    /**
     * 十进制转其他进制
     * @param number
     * @param scale
     * @return
     */
    public static String decimal2Scale(int number, int scale) {
        if (2 > scale || scale > 32) {
            throw new IllegalArgumentException("scale is not in range");
        }
        String result = "";
        while (0 != number) {
            result = number % scale + result;
            number = number / scale;
        }

        return result;
    }

    public static void checkNumber(String number) {
        String regexp = "^\\d+$";
        if (null == number || !number.matches(regexp)) {
            throw new IllegalArgumentException("input is not a number");
        }
    }

    /**
     *
     * 功能描述:int转二进制32位
     *
     * @param:
     * @return:
     * @auther: jintianyun
     * @date: 2020/11/10 14:15
     */
    public static String intToBinary32(int i, int bitNum){
        String binaryStr = Integer.toBinaryString(i);
        while(binaryStr.length() < bitNum){
            binaryStr = "0"+binaryStr;
        }
        return binaryStr;
    }

    /**
     *
     * 功能描述: 16--2
     *
     * @param:
     * @return:
     * @auther: jintianyun
     * @date: 2020/11/10 14:03
     */
    public static String hexString2binaryString(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        String bString = "", tmp;
        for (int i = 0; i < hexString.length(); i++) {
            tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
            bString += tmp.substring(tmp.length() - 4);
        }
        return bString;
    }
    /**
     *
     * 功能描述: 2--16
     *
     * @param:
     * @return:
     * @auther: jintianyun
     * @date: 2020/11/10 14:03
     */
    public static String binaryString2hexString(String bString) {
        if (bString == null || bString.equals("") || bString.length() % 8 != 0)
            return null;
        StringBuffer tmp=new StringBuffer();
        int iTmp = 0;
        for (int i = 0; i < bString.length(); i += 4) {
            iTmp = 0;
            for (int j = 0; j < 4; j++) {
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
            }
            tmp.append(Integer.toHexString(iTmp));
        }
        return tmp.toString();
    }


    /*
     * 十六进制转byte[]数组
     */
    public static byte[] hexStr2bytes(String hexStr) {
        if (StringUtils.isBlank(hexStr)) {
            return null;
        }
        if (hexStr.length() % 2 != 0) {//长度为单数
            hexStr = "0" + hexStr;//前面补0
        }
        char[] chars = hexStr.toCharArray();
        int len = chars.length / 2;
        byte[] bytes = new byte[len];
        for (int i = 0; i < len; i++) {
            int x = i * 2;
            bytes[i] = (byte) Integer.parseInt(String.valueOf(new char[]{chars[x], chars[x + 1]}), 16);
        }
        return bytes;
    }
/**
 *
 * 功能描述:String 转16
 *
 * @param:
 * @return:
 * @auther: jintianyun
 * @date: 2020/10/30 17:19
 */
    public static String strTo16(String s)
    {
        String str="";
        for(int i=0;i<s.length();i++)
        {
            int ch = s.charAt(i);
            String s4 =Integer.toHexString(ch);
            str=str+s4;

        }
        return str;
    }

    /**
     * 16进制转换成为string类型字符串
     *
     * @param s
     * @return
     */
    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "UTF-8");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 功能描述:byte转16
     *
     * @param:
     * @return:
     * @auther: jintianyun
     * @date: 2020/9/17 17:46
     */
    public static String byte2Hex(byte[] bytes, int length) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
//1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    /**
     * 十六进制数隔空位
     *
     * @param str
     * @return
     */
    public static String spaceHex(String str) {
        char[] array = str.toCharArray();
        if (str.length() <= 2) return str;
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            int start = i + 1;
            if (start % 2 == 0) {
                buffer.append(array[i]).append(" ");
            } else {
                buffer.append(array[i]);
            }
        }
        return buffer.toString();
    }

    /**
     * 高位16进制转低位
     *
     * @param str
     * @return
     */
    public static String HighLowHex(String str) {
        if (str.trim().length() <= 2) return str;
        List<String> list = Arrays.asList(str.split(" "));
        Collections.reverse(list);
        StringBuffer stringBuffer = new StringBuffer();
        for (String string : list) {
            stringBuffer.append(string);
        }
        return stringBuffer.toString();
    }

    //length用户要求产生字符串的长度
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 功能描述:从末尾去0
     *
     * @param:
     * @return:
     * @auther: jintianyun
     * @date: 2020/9/23 17:32
     */
    public static String getStr(String str) {
        if(str.length()>48)
        {

            if (str == null) return str;
            StringBuffer tempStr = new StringBuffer();
            char[] chars = str.toCharArray();
            boolean isLast = true;
            int count=0;
            for (int i = chars.length - 1; i >= 0; i--) {
                count++;
                if (isLast) {

                        if (chars[i] != '0') {
                            tempStr.append(chars[i]);
                        }
                        if (tempStr.length() >0) {
                            isLast = false;
                        }

                } else {
                    tempStr.append(chars[i]);
                }
                //System.out.println(str.substring(7,11));
                if(str.substring(8,12).equals("0100")){
                    if(chars.length - count==48){
                        return str.substring(0,str.length()-count);
                    }
                }
            }
            return tempStr.reverse().toString();
        }else {
            return str;
        }
    }


    /**
     * @param str16
     * @return
     * @Date:2014-3-18
     * @Author:lulei
     * @Description: 将16进制的字符串转化为long值
     */
    public static long parseString16ToLong(String str16) {
        if (str16 == null) {
            throw new NumberFormatException("null");
        }
        //先转化为小写
        str16 = str16.toLowerCase();
        //如果字符串以0x开头，去掉0x
        str16 = str16.startsWith("0x") ? str16.substring(2) : str16;
        if (str16.length() > 16) {
            throw new NumberFormatException("For input string '" + str16 + "' is to long");
        }
        return parseMd5L16ToLong(str16);

    }

    /**
     * @param md5L16
     * @return
     * @Date:2014-3-18
     * @Author:lulei
     * @Description: 将16位的md5转化为long值
     */
    public static long parseMd5L16ToLong(String md5L16) {
        if (md5L16 == null) {
            throw new NumberFormatException("null");
        }
        md5L16 = md5L16.toLowerCase();
        byte[] bA = md5L16.getBytes();
        long re = 0L;
        for (int i = 0; i < bA.length; i++) {
            //加下一位的字符时，先将前面字符计算的结果左移4位
            re <<= 4;
            //0-9数组
            byte b = (byte) (bA[i] - 48);
            //A-F字母
            if (b > 9) {
                b = (byte) (b - 39);
            }
            //非16进制的字符
            if (b > 15 || b < 0) {
                throw new NumberFormatException("For input string '" + md5L16);
            }
            re += b;
        }
        return re;
    }

    /**
     *
     * 功能描述:int转16，补0
     *
     * @param:
     * @return: int
     * @auther: jintianyun
     * @date: 2020/10/27 15:37
     */
    public static String intToHex(int n) {
        if (n < 0) {
            n = n + 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexArray[d1] + hexArray[d2];
    }

    /**
     *
     * 功能描述: 16转byte[]
     *
     * @param:
     * @return:
     * @auther: jintianyun
     * @date: 2020/10/28 14:25
     */
    public static byte[] HexStrToBytes(String str)
    {
        //如果字符串长度不为偶数，则追加0
        if(str.length() % 2 !=0){
            str = "0"+str;
        }

        byte[] b = new byte[str.length() / 2];
        byte c1, c2;
        for (int y = 0, x = 0; x < str.length(); ++y, ++x)
        {
            c1 = (byte)str.charAt(x);
            if (c1 > 0x60) c1 -= 0x57;
            else if (c1 > 0x40) c1 -= 0x37;
            else c1 -= 0x30;
            c2 = (byte)str.charAt(++x);
            if (c2 > 0x60) c2 -= 0x57;
            else if (c2 > 0x40) c2 -= 0x37;
            else c2 -= 0x30;
            b[y] = (byte)((c1 << 4) + c2);
        }
        return b;
    }
    }
